﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
//using System.Linq;
using System.Text;
//using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net;
using ICSharpCode.SharpZipLib.Zip;
using System.Diagnostics;

namespace MinecraftLauncher
{
    public partial class Form1 : Form
    {
        string ashFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\.ash\";
        string version = LoginLib.httpGET(@"http://ec2-79-125-102-211.eu-west-1.compute.amazonaws.com/version");

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\";
            if (Directory.Exists(appData + ".ash"))
            {
                if (File.Exists(appData + @".ash\username"))
                {
                    var usernameFile = new StreamReader(appData + @".ash\username");
                    string username = usernameFile.ReadLine();
                    usernameBox.Text = username;
                    usernameFile.Close();

                    if (File.Exists(appData + @".ash\password"))
                    {
                        var passwordFile = new StreamReader(appData + @".ash\password");
                        string password = passwordFile.ReadLine();
                        passwordBox.Text = password;
                        rememberBox.Checked = true;
                        passwordFile.Close();
                    }
                }
            }
            
        }

        private void loginButton_Click(object sender, EventArgs e)
        {
            usernameBox.Enabled = false;
            passwordBox.Enabled = false;
            loginButton.Enabled = false;
            bool folderExists = Directory.Exists(ashFolder);
            bool usernameFileExists = File.Exists(ashFolder + "username");
            bool passwordFileExists = File.Exists(ashFolder + "password");
            bool versionFileExists = File.Exists(ashFolder + "version");
            bool updateForced = forceUpdate.Checked;

            if (!folderExists)
            {
                Directory.CreateDirectory(ashFolder);
            }

            if (passwordBox.Text.Trim() == "" || usernameBox.Text.Trim() == "")
            {
                MessageBox.Show("No username or password entered.");
            }

            if (!versionFileExists)
            {
                var x = File.Create(ashFolder + "version");
                x.Close();
            }

            if (passwordFileExists && !rememberBox.Checked)
            {
                File.Delete(ashFolder + "password");
            }

            if (passwordFileExists && rememberBox.Checked)
            {
                File.Delete(ashFolder + "password");
                var y = File.Create(ashFolder + "password");
                y.Close();
                var passFile = new StreamWriter(ashFolder + "password");
                passFile.WriteLine(passwordBox.Text.Trim());
                passFile.Close();
            }

            if (!passwordFileExists && rememberBox.Checked)
            {
                var y = File.Create(ashFolder + "password");
                y.Close();
                var passFile = new StreamWriter(ashFolder + "password");
                passFile.WriteLine(passwordBox.Text.Trim());
                passFile.Close();
            }

            var z = File.Create(ashFolder + "username");
            z.Close();
            var userFile = new StreamWriter(ashFolder + "username");
            userFile.WriteLine(usernameBox.Text.Trim());
            userFile.Close();

            var versionFile = new StreamReader(ashFolder + "version");
            string versionFromFile = versionFile.ReadLine();
            versionFile.Close();

            if (!folderExists || !versionFileExists || updateForced)
            {
                this.update();
            }

            else if (versionFromFile != version)
            {
                var updating = MessageBox.Show("An update is available would you like to update?", "Update Available", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (updating == DialogResult.Yes)
                {
                    update();
                }
                else
                {
                    load();
                }
            }
            if ((folderExists && versionFileExists) && (!updateForced && (versionFromFile == version)))
            {
                load();
            }
        }

        private void update()
        {
            downloadLabel.Text = "Downloading...";
            var client = new WebClient();
            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
            client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
            client.DownloadFileAsync(new Uri(@"http://ec2-79-125-102-211.eu-west-1.compute.amazonaws.com/" + version + "/file.zip"), ashFolder + "file.zip");
        }

        void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            FastZip fz = new FastZip();
            fz.ExtractZip(ashFolder + "file.zip", ashFolder, null);

            File.Delete(ashFolder + "file.zip");

            var versionFile = new StreamWriter(ashFolder + "version");
            versionFile.WriteLine(version);
            versionFile.Close();
            load();
        }

        public void load()
        {
            string response = LoginLib.generateSession(usernameBox.Text.Trim(), passwordBox.Text.Trim(), 13);
            string[] split = response.Split(':');
            if (split.Length != 5)
            {
                MessageBox.Show("ERROR, Exiting...");
                Application.Exit();
            }

            string sessionID = split[3];
            string username = split[2];
            string textToWrite = "java -Xms256M -Xmx1024M -cp \"" + ashFolder + @"bin\minecraft.jar;" + ashFolder + @"bin\jinput.jar;" + ashFolder + @"bin\lwjgl.jar;" + ashFolder + "bin\\lwjgl_util.jar\" -Djava.library.path=\"" + ashFolder + "bin\\natives\" net.minecraft.client.Minecraft " + username + " " + sessionID;
            var x = File.Create(ashFolder + "launch.bat");
            x.Close();
            var y = new StreamWriter(ashFolder + "launch.bat");
            y.Write(textToWrite);
            y.Close();

            launch();
        }

        public void launch()
        {
            var proc = new Process();
            proc.StartInfo.FileName = ashFolder + "launch.bat";
            //proc.StartInfo.RedirectStandardError = true;
            //proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.UseShellExecute = true;

            proc.Start();
            Application.Exit();
        }

        void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            double bytesIn = double.Parse(e.BytesReceived.ToString());
            double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
            double percentage = bytesIn / totalBytes * 100;

            downloadProgress.Value = int.Parse(Math.Truncate(percentage).ToString());
        }
    }
}
